package com.usian.wemedia.service.impl;

import com.alibaba.nacos.common.util.Md5Utils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.jwt.utils.AppJwtUtil;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends BaseServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmUserDto dto) {
         if (StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword()))return errorParam;
        WmUser one = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (one==null)return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        String password = one.getPassword();
        String s = DigestUtils.md5DigestAsHex((dto.getPassword() + one.getSalt()).getBytes());
        if (s.equals(password)){
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(Long.valueOf(one.getId())));
            one.setSalt(null);
            one.setPassword(null);
            map.put("user",one);
            return ResponseResult.okResult(map);
        }
        return  ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
    }
}